import type { RouteRecordRaw } from "vue-router"
import { getMenus } from "@/common/apis/menus"

import { pinia } from "@/pinia"
import { constantRoutes, dynamicRoutes } from "@/router"

const modules = import.meta.glob("../../pages/**/*.vue")

export function getDynamicRoute(asyncRoute: any[]): RouteRecordRaw[] {
  const newRoute = asyncRoute.map((item) => {
    if (item.component === "Layout" || item.component === "") {
      item.component = () => import("../../layouts/index.vue")
    } else {
      const componentPath = `../../pages/${item.component}.vue`
      if (modules[componentPath]) {
        item.component = modules[componentPath]
      }
    }
    if (item.children && item.children.length > 0) {
      item.children = getDynamicRoute(item.children)
    }
    return item
  })
  return newRoute
}

export const usePermissionStore = defineStore("permission", () => {
  // 可访问的路由
  const routes = ref<RouteRecordRaw[]>([])

  // 有访问权限的动态路由
  const addRoutes = ref<RouteRecordRaw[]>([])

  // 根据角色生成可访问的 Routes（可访问的路由 = 常驻路由 + 有访问权限的动态路由）
  const setRoutes = async () => {
    const res = await getMenus()
    set(getDynamicRoute(res.data))
  }

  // 所有路由 = 所有常驻路由 + 所有动态路由
  const setAllRoutes = () => {
    set(dynamicRoutes)
  }

  // 统一设置
  const set = (accessedRoutes: RouteRecordRaw[]) => {
    routes.value = constantRoutes.concat(accessedRoutes)
    addRoutes.value = accessedRoutes
    console.log("最终设置的路由：", addRoutes.value)
  }

  return { routes, addRoutes, setRoutes, setAllRoutes }
})

/**
 * @description 在 SPA 应用中可用于在 pinia 实例被激活前使用 store
 * @description 在 SSR 应用中可用于在 setup 外使用 store
 */
export function usePermissionStoreOutside() {
  return usePermissionStore(pinia)
}
